package com.liuyi.framework.web.encrypt;

import cn.hutool.core.util.StrUtil;
import com.liuyi.tools.SpringContext;
import com.liuyi.tools.kits.RequestKit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * <p>
 * 加密请求
 * </p>
 *
 * @author Mr.Fmy
 * @since 2021-02-01
 */
@RestControllerAdvice
public class DecodeRequest implements RequestBodyAdvice {

    @Value("${spring.crypto.request.decrypt.charset:UTF-8}")
    private String charset = "UTF-8";
    @Value("${spring.crypto.request.decrypt.key:crypto_decrypt}")
    private String crypto_decrypt = "crypto_decrypt";
    @Resource
    private CryptoFilter cryptoFilter;
    @Value("${spring.crypto.request.decrypt.environment:prd}")
    private String environment = "prd";
    private String active = "";

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        if (StrUtil.isBlank(active)) {
            active = SpringContext.getEnv().getProperty("spring.profiles.active");
        }
        return active.equals(environment) && cryptoFilter.supper() && !cryptoFilter.check(RequestKit.getRequest());
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return new DecryptHttpInputMessage(httpInputMessage, charset, Objects.requireNonNull(RequestKit.getRequest()).getHeader("crypto_decrypt"));
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
